import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { addDays, format } from "date-fns";
import { ProjectAPI } from "@/api/project";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { DocumentTemplateAPI } from "@/api/DocumentTemplate";
import { StandardAPI } from "@/api/Standard";
import { ConductorSpecAPI } from "@/api/ConductorSpec";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

import { RecommendAPI } from "@/api/Recommends";
import { TensionSectionAPI } from "@/api/tensionSection";
import { Button } from "@/components/ui/button";
import { isEqual } from "lodash";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  AlertCircle,
  ChevronLeft,
  Loader2,
  Check,
  AlertTriangle,
  Shield,
  Zap,
  GitCommitHorizontal,
  Anchor,
  FileText,
  Lightbulb,
  X,
  MapPin,
  ChevronUp,
  ChevronDown,
  Pilcrow,
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { Badge } from "@/components/ui/badge";
import { createPageUrl } from "@/utils";
import CompilationBasisTab from "../components/scheme-analyzer/CompilationBasisTab";
import EmergencyPlanTab from "../components/scheme-analyzer/EmergencyPlanTab";
import AcceptanceRequirementsTab from "../components/scheme-analyzer/AcceptanceRequirementsTab";
import StepsManager from "../components/scheme-analyzer/StepsManager";
import ResourceManager from "../components/scheme-analyzer/ResourceManager";
import MeasuresManager from "../components/scheme-analyzer/MeasuresManager";
import SchedulePlanner from "../components/scheme-analyzer/SchedulePlanner";
import DetailsEditor from "../components/scheme-analyzer/DetailsEditor";
import InsulationNettingCalculator from "../components/scheme-analyzer/calculators/InsulationNettingCalculator";
import BearingCableCalculator from "../components/scheme-analyzer/calculators/BearingCableCalculator";
import TemporaryStructureCalculator from "../components/scheme-analyzer/calculators/TemporaryStructureCalculator";
import TractionCalculator from "../components/scheme-analyzer/calculators/TractionCalculator";
import SchemeRecommendation from "../components/scheme-analyzer/SchemeRecommendation";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";

// 辅助组件：导线信息展示卡片
const ConductorInfoCard = ({ conductorSpecId, conductorSpecs }) => {
  const conductor = conductorSpecs?.find((spec) => spec.id === conductorSpecId);
  if (!conductor) return <div className="text-gray-500">未找到导线信息</div>;

  return (
    <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
      <div className="font-medium">{conductor.name}</div>
      <div>截面积: {conductor.crossSectionArea} mm²</div>
      <div>额定拉断力: {conductor.breakingForce} N</div>
      <div>单位重量: {conductor.unitWeight} kg/m</div>
    </div>
  );
};

const ENGINEERINGCALCULATORS = [
  {
    id: "netting",
    name: "绝缘绳网",
    icon: Shield,
    component: InsulationNettingCalculator,
  },
  {
    id: "bearing-cable",
    name: "承载索与净空校验",
    icon: Zap,
    component: BearingCableCalculator,
  },
  {
    id: "traction",
    name: "牵引计算",
    icon: GitCommitHorizontal,
    component: TractionCalculator,
  },
  {
    id: "temporary-structure",
    name: "临时装置受力分析",
    icon: Anchor,
    component: TemporaryStructureCalculator,
  },
];

export default function SchemeAnalysis({ schemeId: schemeIdProp, onClose }) {
  const [crossingTypeMap, setCrossingTypeMap] = useState({});
  const [isLoadingCrossingTypes, setIsLoadingCrossingTypes] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const { toast } = useToast();
  const [allTowersInSection, setAllTowersInSection] = useState([]);
  const [scheme, setScheme] = useState(null);
  const [crossingPoint, setCrossingPoint] = useState(null);
  const [project, setProject] = useState(null);
  const [standards, setStandards] = useState([]);
  const [documentTemplates, setDocumentTemplates] = useState([]);
  const [isGeneratingDoc, setIsGeneratingDoc] = useState(false);
  const [isGeneratingWord, setIsGeneratingWord] = useState(false);
  const [showRecommendation, setShowRecommendation] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState("details");
  const [activeSubTab, setActiveSubTab] = useState("netting");
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [stepsUpdateCount, setStepsUpdateCount] = useState(0);
  const [allProjects, setAllProjects] = useState([]);
  const [isRatingModalOpen, setIsRatingModalOpen] = useState(false);
  const [recommendationData, setRecommendationData] = useState(null);
  const [selectedConstructionMethod, setSelectedConstructionMethod] =
    useState(null);
  // 修改：将关联工程数据栏默认状态改为收起
  const [isDataSectionOpen, setIsDataSectionOpen] = useState(false);
  const [selectedCrossingPoints, setSelectedCrossingPoints] = useState([]);
  const [conductorSpecs, setConductorSpecs] = useState([]);
  const [lastScheduleUpdate, setLastScheduleUpdate] = useState(0);

  // 获取跨越类型字典数据
  const loadCrossingTypeDictionary = useCallback(async () => {
    try {
      setIsLoadingCrossingTypes(true);
      const typeResponse = await DictTypeAPI.getList();
      const crossingType = typeResponse.rows?.find(
        (item) => item.dictName == "跨越类型"
      );

      if (!crossingType?.dictType) {
        setCrossingTypeMap({});
        return;
      }
      const dataResponse = await DictDataAPI.getList({
        dictType: crossingType.dictType,
      });

      const typeMap = {};
      (dataResponse.rows || []).forEach((item) => {
        if (item.dictValue && item.dictLabel) {
          typeMap[item.dictValue] = item.dictLabel;
        }
      });
      setCrossingTypeMap(typeMap);
    } catch (error) {
      console.error("❌ 加载跨越类型字典失败:", error);
      toast({
        variant: "destructive",
        title: "字典数据加载失败",
        description: "跨越类型显示将使用原始编码，请联系管理员检查接口配置",
      });
      setCrossingTypeMap({});
    } finally {
      setIsLoadingCrossingTypes(false);
    }
  }, []);

  // 组件挂载时加载跨越类型字典
  useEffect(() => {
    loadCrossingTypeDictionary();
  }, [loadCrossingTypeDictionary]);

  // 获取导线规格数据
  const loadConductorSpecs = useCallback(async (tensionSectionId) => {
    if (!tensionSectionId) return;
    try {
      const response = await ConductorSpecAPI.getList();
      setConductorSpecs(response.data || []);
    } catch (err) {
      setConductorSpecs([]);
    }
  }, []);

  // 获取跨越点列表
  const loadCrossingPoints = useCallback(async (projectId) => {
    if (!projectId) return;
    try {
      const response = await CrossingPointAPI.getList({ projectId });
      setSelectedCrossingPoints(response.data || []);
    } catch (err) {
      console.warn("加载跨越点数据失败:", err);
      setSelectedCrossingPoints([]);
    }
  }, []);

  const handRecommendation = async () => {
    try {
      if (!scheme?.tensionSectionId) {
        throw new Error("未找到有效的跨越点ID，请先完善方案基础信息");
      }
      let recommendationData;
      const response = await RecommendAPI.aiRecommend(scheme.tensionSectionId);
      if (!response || !response.data) {
        throw new Error(response?.msg || "未获取到有效的推荐数据");
      }
      recommendationData = response.data;
      handleRecommendationSuccess(recommendationData);
    } catch (error) {
      console.error("智能推荐失败:", error);
      const errorType = error.message.includes("未找到")
        ? "数据缺失"
        : error.message.includes("超时")
        ? "请求超时"
        : "系统错误";

      toast({
        variant: "destructive",
        title: `推荐失败（${errorType}）`,
        description: error.message || "生成智能推荐时发生错误，请稍后重试",
      });
    }
  };

  const handleRecommendationSuccess = (data) => {
    setRecommendationData(data);
    setShowRecommendation(true);
  };

  const handleGenerateDocument = async () => {
    if (!scheme) {
      toast({
        variant: "destructive",
        title: "生成失败",
        description: "未找到有效的方案数据",
      });
      return;
    }

    if (!scheme.documentTemplateId) {
      toast({
        variant: "destructive",
        title: "未选择文档模板",
        description: "请先在方案详情中选择文档模板",
      });
      return;
    }

    setIsGeneratingDoc(true);

    try {
      const abortController = new AbortController();
      const timeoutId = setTimeout(() => abortController.abort(), 60000);

      const response = await ConstructionSchemeAPI.exportWord(scheme.id, {
        signal: abortController.signal,
      });

      clearTimeout(timeoutId);

      if (!response.data) {
        throw new Error("未获取到文档数据");
      }

      if (!(response.data instanceof Blob)) {
        let errorData;
        const text = await response.data.text();
        errorData = JSON.parse(text);
        throw new Error(errorData?.message || "服务器返回错误，无法生成文档");
      }

      const rawFileName =
        response.headers["download-filename"] ||
        response.headers["Download-Filename"];

      let downloadFileName = rawFileName
        ? decodeURIComponent(rawFileName)
        : `施工方案_${scheme.name || scheme.id}.docx`;

      if (!downloadFileName.endsWith(".docx")) {
        downloadFileName = `${downloadFileName.replace(/\.[^/.]+$/, "")}.docx`;
      }

      const wordMimeType =
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const fileBlob = new Blob([response.data], { type: wordMimeType });
      const url = window.URL.createObjectURL(fileBlob);

      const a = document.createElement("a");
      a.href = url;
      a.download = downloadFileName;
      document.body.appendChild(a);

      try {
        a.click();
        toast({
          title: "生成成功",
          description: `文档已开始下载：${downloadFileName}`,
        });
      } catch (clickError) {
        console.error("下载触发失败:", clickError);
        toast({
          variant: "destructive",
          title: "下载失败",
          description: "无法自动触发下载，请手动保存文件",
        });
        window.open(url, "_blank");
      } finally {
        setTimeout(() => {
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        }, 1000);
      }
    } catch (error) {
      console.error("生成文档错误:", error);
      const errorMessage =
        error.name === "AbortError"
          ? "生成超时，请尝试简化方案内容或稍后重试"
          : error.message || "生成Word文档失败，请检查网络连接后重试";

      toast({
        variant: "destructive",
        title: "生成失败",
        description: errorMessage,
      });
    } finally {
      setIsGeneratingDoc(false);
    }
  };

  const getSchemeId = useCallback(() => {
    if (
      schemeIdProp &&
      typeof schemeIdProp === "string" &&
      schemeIdProp.length >= 16
    ) {
      return schemeIdProp;
    }

    const searchParamId = searchParams.get("id");
    if (searchParamId && searchParamId.length >= 16) {
      return searchParamId;
    }

    try {
      const windowParams = new URLSearchParams(window.location.search);
      const windowParamId = windowParams.get("id");
      if (windowParamId && windowParamId.length >= 16) {
        return windowParamId;
      }
    } catch (e) {
      console.error("方法3失败 - 解析window.location.search出错:", e);
    }

    const stateId = location.state?.schemeId;
    if (stateId && stateId.length >= 16) {
      return stateId;
    }

    try {
      const pathname = location.pathname || window.location.pathname;
      const segments = pathname.split("/").filter((s) => s.length > 0);

      for (const segment of segments) {
        if (segment.length >= 16 && segment.length <= 32) {
          return segment;
        }
      }
    } catch (e) {
      console.error("方法5失败 - 路径解析出错:", e);
    }

    return null;
  }, [schemeIdProp, searchParams, location]);

  // 加载数据
  const loadData = useCallback(async () => {
    const schemeId = getSchemeId();
    if (!schemeId) {
      const errorMsg = "无法获取方案ID，请检查URL或重新从施工方案列表进入。";
      setError(errorMsg);
      setIsLoading(false);
      return;
    }

    setError(null);
    setIsLoading(true);

    try {
      // 并行加载基础数据
      const [resStandard, resProject] = await Promise.all([
        StandardAPI.getList(),
        ProjectAPI.getList(),
      ]);

      setAllProjects(resProject.data);
      setStandards(resStandard.data);

      // 加载方案基础数据
      const res = await ConstructionSchemeAPI.get(schemeId);
      const targetScheme = res.data;

      if (!targetScheme) {
        throw new Error("施工方案不存在或已被删除");
      }
      setScheme(targetScheme);

      // 加载导线规格数据（独立于主流程，避免阻塞）
      if (targetScheme.tensionSectionId) {
        loadConductorSpecs(targetScheme.tensionSectionId);
      }

      // 并行加载关联数据
      await Promise.all([
        targetScheme.tensionSectionId
          ? TensionSectionAPI.getDetail(targetScheme.tensionSectionId).then(
              (res) => {
                setAllTowersInSection(res.data?.towerList || []);
                const cp = res.data;
                setCrossingPoint(cp);
                if (cp?.projectId) {
                  return Promise.all([
                    ProjectAPI.get(cp.projectId).then((projRes) => {
                      const proj = projRes.data;
                      setProject(proj);
                      return proj;
                    }),
                    loadCrossingPoints(cp.projectId),
                  ]);
                }
              }
            )
          : Promise.resolve(),

        DocumentTemplateAPI.getList()
          .then((tplRes) => {
            setDocumentTemplates(Array.isArray(tplRes.data) ? tplRes.data : []);
          })
          .catch((tplErr) => {
            console.warn("⚠️ 文档模板加载失败:", tplErr);
            setDocumentTemplates([]);
          }),
      ]);

      console.log("🎉 所有数据加载完成");
    } catch (err) {
      console.error("❌ 加载方案分析数据时发生错误:", err);
      const errorMessage =
        err.message?.includes("not found") || err.message?.includes("不存在")
          ? "找不到指定的施工方案，可能已被删除或ID不正确。"
          : "加载数据失败: " + (err.message || "未知错误");
      setError(errorMessage);
      setScheme(null);
      setCrossingPoint(null);
      setProject(null);
    } finally {
      setIsLoading(false);
    }
  }, [getSchemeId, loadCrossingPoints, loadConductorSpecs]);

  // 只在location或schemeId变化时重新加载数据
  useEffect(() => {
    const schemeId = getSchemeId();
    if (schemeId) {
      loadData();
    }
  }, [getSchemeId, loadData, location.pathname]);

  const hasCycleInSteps = useCallback((steps) => {
    if (!steps || !steps.length) return false;

    const stepMap = {};
    steps.forEach((step) => {
      stepMap[step.stepOrder] = step;
    });

    const visited = {};
    steps.forEach((step) => {
      visited[step.stepOrder] = 0;
    });

    const dfs = (stepId) => {
      if (visited[stepId] === 1) {
        return true;
      }
      if (visited[stepId] === 2) {
        return false;
      }

      visited[stepId] = 1;
      const step = stepMap[stepId];
      if (!step) return false;

      const predecessors = step.predecessorSteps || [];
      for (const predId of predecessors) {
        if (dfs(predId)) {
          return true;
        }
      }

      visited[stepId] = 2;
      return false;
    };

    for (const step of steps) {
      if (visited[step.stepOrder] === 0) {
        if (dfs(step.stepOrder)) {
          return true;
        }
      }
    }

    return false;
  }, []);

  const memoizedScheme = useMemo(() => scheme, [scheme]);
  const memoizedSteps = useMemo(
    () => scheme?.constructionSteps || [],
    [scheme?.constructionSteps, stepsUpdateCount]
  );
  const hasCycle = useMemo(
    () => hasCycleInSteps(memoizedSteps),
    [memoizedSteps, hasCycleInSteps]
  );

  const handleUpdate = async (updatedFields) => {
    if (!scheme) return;

    // 检查是否真的有变化
    let hasChanges = Object.entries(updatedFields).some(([key, value]) => {
      return !isEqual(scheme[key], value);
    });

    if (!hasChanges) return;

    const updatedScheme = { ...scheme, ...updatedFields };
    setScheme(updatedScheme);
    setHasUnsavedChanges(true);

    // 仅在更新施工步骤时才增加计数器
    if ("constructionSteps" in updatedFields) {
      setStepsUpdateCount((prev) => prev + 1);
    }
  };

  const updateScheduleFromSteps = useCallback(() => {
    // 防抖动：避免短时间内多次更新
    if (Date.now() - lastScheduleUpdate < 500) {
      return;
    }

    if (!scheme?.constructionSteps || !scheme.constructionSteps.length) return;
    if (hasCycle) {
      toast({
        variant: "destructive",
        title: "无法更新进度计划",
        description: "施工步骤中存在循环依赖，请先修正步骤关系",
      });
      return;
    }

    const scheduledSteps = [...scheme.constructionSteps]
      .sort((a, b) => a.stepOrder - b.stepOrder)
      .map((step, index) => {
        let startDate;
        if (
          index === 0 ||
          !step.predecessorSteps ||
          step.predecessorSteps.length === 0
        ) {
          startDate = new Date();
        } else {
          const lastPredecessorOrder = Math.max(...step.predecessorSteps);
          const lastPredecessor = scheme.constructionSteps.find(
            (s) => s.stepOrder === lastPredecessorOrder
          );
          startDate = lastPredecessor?.endDate
            ? addDays(new Date(lastPredecessor.endDate), 1)
            : new Date();
        }

        const durationDays = step.durationDays || 1;
        const endDate = addDays(startDate, durationDays - 1);

        return { ...step, startDate, endDate };
      });

    const formattedPlanTable = scheduledSteps.map((step) => ({
      stepOrder: step.stepOrder,
      stepName: step.stepName,
      durationDays: step.durationDays || 1,
      predecessorSteps: step.predecessorSteps?.join(", ") || "无",
      startDate: format(step.startDate, "yyyy-MM-dd"),
      endDate: format(step.endDate, "yyyy-MM-dd"),
      remark: step.remark || "",
    }));

    // 检查是否有实际变化，避免不必要的更新
    const isPlanDifferent = !isEqual(
      formattedPlanTable,
      scheme.planDetailTable
    );

    if (isPlanDifferent) {
      handleUpdate({
        constructionSteps: scheduledSteps,
        planDetailTable: formattedPlanTable,
      });
      setLastScheduleUpdate(Date.now());
    }
  }, [scheme, hasCycle, handleUpdate, lastScheduleUpdate]);

  // 优化进度计划更新逻辑，避免无限循环
  useEffect(() => {
    if (scheme?.constructionSteps?.length && stepsUpdateCount > 0) {
      // 使用setTimeout避免同步更新导致的循环
      const timer = setTimeout(() => {
        updateScheduleFromSteps();
      }, 300);

      return () => clearTimeout(timer);
    }
  }, [
    stepsUpdateCount,
    scheme?.constructionSteps?.length,
    updateScheduleFromSteps,
  ]);

  const handleSave = async () => {
    if (!scheme || !hasUnsavedChanges) return;
    setIsSaving(true);
    try {
      await ConstructionSchemeAPI.update(scheme.id, scheme);
      setHasUnsavedChanges(false);
      toast({
        title: "保存成功",
        description: "方案信息已保存。",
        className: "bg-green-100 text-green-800",
      });
    } catch (error) {
      console.error("保存方案失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: "保存方案信息时出错: " + error.message,
      });
    } finally {
      setIsSaving(false);
    }
  };

  // const renderActiveCalculatorContent = useCallback(() => {
  //   const activeCalculator = ENGINEERINGCALCULATORS.find(
  //     (c) => c.id === activeSubTab
  //   );
  //   if (!activeCalculator) {
  //     return <p>请选择一个计算模块</p>;
  //   }

  //   const CalculatorComponent = activeCalculator.component;
  //   return (
  //     <CalculatorComponent
  //       scheme={scheme}
  //       onUpdate={handleUpdate}
  //       crossingPoint={crossingPoint}
  //       crossingTypeMap={crossingTypeMap}
  //     />
  //   );
  // }, [activeSubTab, scheme, handleUpdate, crossingPoint, crossingTypeMap]);
// 在 SchemeAnalysis 组件中找到 renderActiveCalculatorContent 函数，修改为：
const renderActiveCalculatorContent = useCallback(() => {
  const activeCalculator = ENGINEERINGCALCULATORS.find(
    (c) => c.id === activeSubTab
  );
  if (!activeCalculator) {
    return <p>请选择一个计算模块</p>;
  }

  const CalculatorComponent = activeCalculator.component;
  
  // 确保正确传递 crossingPointList
  const crossingPointListData = crossingPoint?.crossingPointList || [];
  console.log("传递给计算器的 crossingPointList:", crossingPointListData);
  
  return (
    <CalculatorComponent
      scheme={scheme}
      onUpdate={handleUpdate}
      crossingPoint={crossingPoint}
      crossingPointList={crossingPointListData} // 传递 crossingPointList
      crossingTypeMap={crossingTypeMap}
    />
  );
}, [activeSubTab, scheme, handleUpdate, crossingPoint, crossingTypeMap]);

  const handleBack = () => {
    if (onClose) {
      onClose();
    } else {
      navigate(createPageUrl("ConstructionSchemes"));
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <Loader2 className="w-12 h-12 animate-spin text-blue-600 mx-auto" />
          <p className="mt-4 text-lg text-gray-600">正在加载方案数据...</p>
          <p className="text-sm text-gray-400">
            方案ID: {getSchemeId() || "检测中..."}
          </p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>加载错误</AlertTitle>
          <AlertDescription>
            {error}
            <div className="mt-4 space-y-2">
              <p className="text-sm font-medium">调试信息:</p>
              <p className="text-xs">当前URL: {window.location.href}</p>
              <p className="text-xs">检测到的方案ID: {getSchemeId() || "无"}</p>
              <p className="text-xs">传入的方案ID: {schemeIdProp || "无"}</p>
              <p className="text-xs">
                SearchParams ID: {searchParams.get("id") || "无"}
              </p>
              <div className="flex gap-2 mt-4">
                <Button onClick={handleBack}>
                  <ChevronLeft className="w-4 h-4 mr-2" />
                  返回方案列表
                </Button>
                <Button
                  onClick={() => window.location.reload()}
                  variant="outline"
                >
                  刷新页面
                </Button>
                <Button onClick={() => loadData()} variant="outline">
                  重试加载
                </Button>
              </div>
            </div>
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  if (!scheme) {
    return (
      <div className="p-8 text-center">
        <p className="text-gray-500">未找到方案数据。</p>
        <Button onClick={handleBack} className="mt-4">
          <ChevronLeft className="w-4 h-4 mr-2" />
          返回方案列表
        </Button>
      </div>
    );
  }

  return (
    <div className="p-4 sm:p-6 lg:p-8 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <header className="mb-8">
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <Button
                variant="outline"
                size="icon"
                className="h-9 w-9"
                onClick={handleBack}
              >
                <ChevronLeft className="h-5 w-5" />
              </Button>
              <div>
                <h1
                  className="text-2xl md:text-3xl font-bold text-gray-900 line-clamp-1"
                  title={scheme.name}
                >
                  {scheme.name}
                </h1>
                <div className="flex items-center gap-4 text-sm text-gray-500 mt-1">
                  <span>{project?.projectName || "未知项目"}</span>
                  <span>/</span>
                  <span>{crossingPoint?.name || "未知跨越点"}</span>
                  <Badge
                    variant="outline"
                    className={
                      scheme?.approvalStatus === "completed"
                        ? "text-green-700 border-green-300"
                        : scheme?.approvalStatus === "inProgress"
                        ? "text-blue-700 border-blue-300"
                        : "text-gray-700 border-gray-300"
                    }
                  >
                    {scheme?.approvalStatus === "completed"
                      ? "已完工"
                      : scheme?.approvalStatus === "inProgress"
                      ? "已开工"
                      : "未开工"}
                  </Badge>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button
                disabled={isGeneratingDoc || isLoadingCrossingTypes}
                variant="outline"
                className="text-white bg-purple-600 hover:bg-purple-700 text-white "
                onClick={handRecommendation}
              >
                <Lightbulb className="w-4 h-4 mr-2" />
                智能推荐
              </Button>
              <Button
                onClick={handleGenerateDocument}
                disabled={
                  isLoading ||
                  isSaving ||
                  hasUnsavedChanges ||
                  isLoadingCrossingTypes
                }
                variant="outline"
                className="bg-green-600 hover:bg-green-700 text-white disabled:bg-green-300"
              >
                {isGeneratingWord ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    生成中...
                  </>
                ) : (
                  <>
                    <FileText className="w-4 h-4 mr-2" />
                    生成Word
                  </>
                )}
              </Button>
            </div>
          </div>
        </header>

        {showRecommendation && (
          <SchemeRecommendation
            recommendationData={recommendationData}
            onClose={() => setShowRecommendation(false)}
            onApplyRecommendation={(method) => {
              setSelectedConstructionMethod({
                id: method.id,
                name: method.methodName,
                timestamp: Date.now(),
              });
              handleUpdate({
                constructionMethodId: method.id,
                constructionMethodName: method.methodName,
              });
              setShowRecommendation(false);
            }}
          />
        )}

        {(allTowersInSection.length > 0 ||
          selectedCrossingPoints.length > 0 ||
          scheme?.conductorSpecId ||
          project?.conductorSpecId) && (
          <Collapsible
            open={isDataSectionOpen}
            onOpenChange={setIsDataSectionOpen}
            className="w-full mb-6"
          >
            <Card>
              <CollapsibleTrigger asChild>
                <CardHeader className="cursor-pointer hover:bg-gray-50 transition-colors">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <MapPin className="w-5 h-5 text-blue-600" />
                      <CardTitle className="text-lg">关联工程数据</CardTitle>
                      {allTowersInSection.length > 0 && (
                        <Badge variant="secondary">
                          {allTowersInSection.length} 座杆塔
                        </Badge>
                      )}
                      {crossingPoint?.crossingPointList?.length > 0 && (
                        <Badge variant="outline">
                          {crossingPoint.crossingPointList.length} 个跨越点
                        </Badge>
                      )}
                      {isLoadingCrossingTypes && (
                        <Badge variant="outline" className="text-xs">
                          <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                          加载类型...
                        </Badge>
                      )}
                    </div>
                    {isDataSectionOpen ? (
                      <ChevronUp className="w-5 h-5 text-gray-500" />
                    ) : (
                      <ChevronDown className="w-5 h-5 text-gray-500" />
                    )}
                  </div>
                  <CardDescription>
                    查看本方案关联的杆塔位置、跨越点详情及导线信息
                  </CardDescription>
                </CardHeader>
              </CollapsibleTrigger>
              <CollapsibleContent>
                <CardContent className="pt-0 space-y-6">
                  {(scheme?.conductorSpecId || project?.conductorSpecId) && (
                    <div>
                      <div className="flex items-center gap-2 mb-3">
                        <GitCommitHorizontal className="w-4 h-4 text-green-600" />
                        <h3 className="font-semibold text-gray-900">
                          导线信息
                        </h3>
                      </div>
                      <Card className="bg-gradient-to-br from-green-50 to-white border-green-200">
                        <CardContent className="p-4">
                          <ConductorInfoCard
                            conductorSpecId={
                              scheme?.conductorSpecId ||
                              project?.conductorSpecId
                            }
                            conductorSpecs={conductorSpecs}
                          />
                        </CardContent>
                      </Card>
                    </div>
                  )}

                  {allTowersInSection.length > 0 && (
                    <div>
                      <div className="flex items-center gap-2 mb-3">
                        <Pilcrow className="w-4 h-4 text-indigo-600" />
                        <h3 className="font-semibold text-gray-900">
                          杆塔列表
                        </h3>
                      </div>
                      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                        {allTowersInSection.map((tower, index) => (
                          <Card
                            key={tower.id}
                            className="bg-gradient-to-br from-indigo-50 to-white border-indigo-200"
                          >
                            <CardContent className="p-4">
                              <div className="flex items-start justify-between mb-2">
                                <div className="flex items-center gap-2">
                                  <div className="w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center">
                                    <span className="text-sm font-bold text-indigo-700">
                                      {index + 1}
                                    </span>
                                  </div>
                                  <span className="font-semibold text-gray-900">
                                    {tower.towerNumber}
                                  </span>
                                </div>
                                <Badge variant="outline" className="text-xs">
                                  {tower.type === "tensionTower" && "耐张塔"}
                                  {tower.type === "straightLineTower" &&
                                    "直线塔"}
                                  {tower.type === "angleTower" && "转角塔"}
                                  {tower.type === "branchTower" && "分支塔"}
                                </Badge>
                              </div>
                              <div className="space-y-1 text-sm text-gray-600">
                                {tower.height && (
                                  <div className="flex justify-between">
                                    <span>塔高:</span>
                                    <span className="font-medium">
                                      {tower.height} m
                                    </span>
                                  </div>
                                )}
                                {tower.groundElevation && (
                                  <div className="flex justify-between">
                                    <span>呼称高:</span>
                                    <span className="font-medium">
                                      {tower.groundElevation} m
                                    </span>
                                  </div>
                                )}
                                {tower.latitude && tower.longitude && (
                                  <div className="text-xs text-gray-500 mt-2">
                                    <div>纬度: {tower.latitude}</div>
                                    <div>经度: {tower.longitude}</div>
                                  </div>
                                )}
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    </div>
                  )}

                  {crossingPoint?.crossingPointList?.length > 0 && (
                    <div>
                      <div className="flex items-center gap-2 mb-3">
                        <MapPin className="w-4 h-4 text-red-600" />
                        <h3 className="font-semibold text-gray-900">跨越点</h3>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {crossingPoint.crossingPointList.map((cp) => (
                          <Card
                            key={cp.id}
                            className="bg-gradient-to-br from-red-50 to-white border-red-200"
                          >
                            <CardContent className="p-4">
                              <div className="flex items-start justify-between mb-3">
                                <div>
                                  <h4 className="font-semibold text-gray-900">
                                    {cp.name}
                                  </h4>
                                  <p className="text-sm text-gray-600 mt-1">
                                    {cp.crossingObject || "无描述"}
                                  </p>
                                </div>
                                <Badge
                                  variant={
                                    cp.difficultyLevel === "critical"
                                      ? "destructive"
                                      : cp.difficultyLevel === "high"
                                      ? "default"
                                      : "secondary"
                                  }
                                >
                                  {cp.difficultyLevel === "critical" &&
                                    "极高难度"}
                                  {cp.difficultyLevel === "high" && "高难度"}
                                  {cp.difficultyLevel === "medium" &&
                                    "中等难度"}
                                  {cp.difficultyLevel === "low" && "低难度"}
                                </Badge>
                              </div>
                              <div className="grid grid-cols-4 gap-2 text-sm">
                                <div className="col-span-4 flex">
                                  <span className="text-gray-600">
                                    跨越类型:
                                  </span>
                                  <div className="font-medium text-gray-900">
                                    {isLoadingCrossingTypes ? (
                                      <span className="text-gray-400">
                                        加载中...
                                      </span>
                                    ) : (
                                      crossingTypeMap[cp.crossingType] ||
                                      cp.crossingType ||
                                      "未知类型"
                                    )}
                                  </div>
                                </div>
                                {cp.spanLength && (
                                  <div className="col-span-2 flex">
                                    <span className="text-gray-600">档距:</span>
                                    <div className="font-medium text-gray-900">
                                      {cp.spanLength} m
                                    </div>
                                  </div>
                                )}
                                {cp.crossingHeight && (
                                  <div className="col-span-2 flex">
                                    <span className="text-gray-600">高度:</span>
                                    <div className="font-medium text-gray-900">
                                      {cp.crossingHeight} m
                                    </div>
                                  </div>
                                )}
                                {cp.crossedObjectWidth && (
                                  <div className="col-span-2 flex">
                                    <span className="text-gray-600">宽度:</span>
                                    <div className="font-medium text-gray-900">
                                      {cp.crossedObjectWidth} m
                                    </div>
                                  </div>
                                )}
                                {cp.crossingAngle && (
                                  <div className="col-span-2 flex">
                                    <span className="text-gray-600">
                                      交叉角度:
                                    </span>
                                    <div className="font-medium text-gray-900">
                                      {cp.crossingAngle}°
                                    </div>
                                  </div>
                                )}
                                {cp.conductorType && (
                                  <div className="col-span-2 flex">
                                    <span className="text-gray-600">
                                      导线型号:
                                    </span>
                                    <div className="font-medium text-gray-900">
                                      {cp.conductorType}
                                    </div>
                                  </div>
                                )}
                              </div>
                              <div className="flex flex-wrap gap-2 mt-3">
                                {cp.requiresPowerOutage && (
                                  <Badge variant="outline" className="text-xs">
                                    <Zap className="w-3 h-3 mr-1" />
                                    需停电
                                  </Badge>
                                )}
                                {cp.requiresLiveWork && (
                                  <Badge variant="outline" className="text-xs">
                                    <Shield className="w-3 h-3 mr-1" />
                                    需带电作业
                                  </Badge>
                                )}
                                {cp.requiresRoadClosure && (
                                  <Badge variant="outline" className="text-xs">
                                    封路
                                  </Badge>
                                )}
                                {cp.requiresTrafficControl && (
                                  <Badge variant="outline" className="text-xs">
                                    交通管制
                                  </Badge>
                                )}
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </CollapsibleContent>
            </Card>
          </Collapsible>
        )}

        <Tabs
          value={activeTab}
          onValueChange={setActiveTab}
          className="w-full "
        >
          <TabsList className="grid w-full grid-cols-3 md:grid-cols-9 mb-6">
            <TabsTrigger value="details" className="relative">
              方案详情
              {hasUnsavedChanges && activeTab === "details" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="compilation" className="relative">
              编制依据
              {hasUnsavedChanges && activeTab === "compilation" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="engineering" className="relative">
              工程计算
              {hasUnsavedChanges && activeTab === "engineering" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="steps" className="relative">
              施工步骤
              {hasUnsavedChanges && activeTab === "steps" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="schedule" className="relative">
              进度计划
              {hasUnsavedChanges && activeTab === "schedule" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="resources" className="relative">
              资源配置
              {hasUnsavedChanges && activeTab === "resources" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="measures" className="relative">
              风险辨识与控制措施
              {hasUnsavedChanges && activeTab === "measures" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="emergency" className="relative">
              应急预案
              {hasUnsavedChanges && activeTab === "emergency" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
            <TabsTrigger value="acceptance" className="relative">
              验收要求
              {hasUnsavedChanges && activeTab === "acceptance" && (
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-orange-500 rounded-full"></span>
              )}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="details" className="space-y-6">
            <DetailsEditor
              scheme={memoizedScheme}
              onUpdate={handleUpdate}
              crossingPoint={crossingPoint}
              selectedConstructionMethod={selectedConstructionMethod}
              crossingTypeMap={crossingTypeMap}
              isLoadingCrossingTypes={isLoadingCrossingTypes}
            />
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="acceptance" className="space-y-6">
            <AcceptanceRequirementsTab
              scheme={scheme}
              onUpdate={handleUpdate}
              isLoading={isLoading}
            />
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="compilation" className="space-y-6">
            <CompilationBasisTab
              scheme={scheme}
              onUpdate={handleUpdate}
              standards={standards}
              isLoading={isLoading}
            />
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="steps" className="space-y-6">
            <StepsManager
              scheme={scheme}
              onUpdate={handleUpdate}
              isLoading={isLoading}
              onStepsChange={() => setStepsUpdateCount((prev) => prev + 1)}
            />

            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="resources" className="space-y-6">
            <ResourceManager
              scheme={scheme}
              onUpdate={handleUpdate}
              isLoading={isLoading}
            />
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="measures" className="space-y-6">
            <MeasuresManager
              scheme={scheme}
              onUpdate={handleUpdate}
              crossingPoint={crossingPoint}
              project={project}
              crossingTypeMap={crossingTypeMap}
            />
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="schedule" className="space-y-6">
            <SchedulePlanner
              scheme={scheme}
              onUpdate={handleUpdate}
              isLoading={isLoading}
              stepsUpdateCount={stepsUpdateCount}
              onScheduledStepsChange={(scheduledSteps) => {
                if (hasCycle) return;

                const formattedPlanTable = scheduledSteps.map((step) => ({
                  stepOrder: step.stepOrder,
                  stepName: step.stepName,
                  durationDays: step.durationDays || 1,
                  predecessorSteps: step.predecessorSteps?.join(", ") || "无",
                  startDate: step.startDate
                    ? format(step.startDate, "yyyy-MM-dd")
                    : "",
                  endDate: step.endDate
                    ? format(step.endDate, "yyyy-MM-dd")
                    : "",
                  remark: step.remark || "",
                }));

                const currentPlanTable = scheme.planDetailTable || [];
                let plansEqual = true;

                if (formattedPlanTable.length !== currentPlanTable.length) {
                  plansEqual = false;
                } else {
                  for (let i = 0; i < formattedPlanTable.length; i++) {
                    const newPlan = formattedPlanTable[i];
                    const oldPlan = currentPlanTable[i];

                    if (
                      newPlan.stepOrder !== oldPlan.stepOrder ||
                      newPlan.stepName !== oldPlan.stepName ||
                      newPlan.durationDays !== oldPlan.durationDays ||
                      newPlan.predecessorSteps !== oldPlan.predecessorSteps ||
                      newPlan.startDate !== oldPlan.startDate ||
                      newPlan.endDate !== oldPlan.endDate ||
                      newPlan.remark !== oldPlan.remark
                    ) {
                      plansEqual = false;
                      break;
                    }
                  }
                }

                if (!plansEqual) {
                  handleUpdate({ planDetailTable: formattedPlanTable });
                }
              }}
            />
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="engineering" className="space-y-6">
            <div className="grid grid-cols-1 lg:grid-cols-1 gap-6">
              <Alert
                variant="default"
                className="bg-yellow-50 border-yellow-200 text-yellow-800"
              >
                <AlertTriangle className="h-4 w-4 !text-yellow-600" />
                <AlertDescription>
                  <strong>免责声明：</strong>
                  此模块提供的所有计算结果均基于通用模型和输入参数，仅供参考。最终方案设计与施工决策必须由具备资质的专业工程师根据现场实际情况、详细勘测数据和相关国家/行业标准进行复核与确认。
                </AlertDescription>
              </Alert>

              <Tabs
                value={activeSubTab}
                onValueChange={setActiveSubTab}
                className="w-full"
              >
                <TabsList
                  className="grid w-full"
                  style={{
                    gridTemplateColumns: `repeat(${ENGINEERINGCALCULATORS.length}, minmax(0, 1fr))`,
                  }}
                >
                  {ENGINEERINGCALCULATORS.map((calc) => (
                    <TabsTrigger
                      key={calc.id}
                      value={calc.id}
                      className="flex items-center gap-2"
                    >
                      {calc.icon && <calc.icon className="w-4 h-4" />}
                      {calc.name}
                    </TabsTrigger>
                  ))}
                </TabsList>

                <TabsContent value={activeSubTab} className="mt-6">
                  {renderActiveCalculatorContent()}
                </TabsContent>
              </Tabs>
            </div>
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="emergency" className="pt-4">
            <EmergencyPlanTab
              scheme={scheme}
              onUpdate={handleUpdate}
              crossingTypeMap={crossingTypeMap}
            />
            <div className="flex justify-end pt-6 border-t bg-gray-50/50">
              <Button
                onClick={handleSave}
                disabled={!hasUnsavedChanges || isSaving}
                className="px-8"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4 mr-2" />
                    {hasUnsavedChanges ? "保存更改" : "已保存"}
                  </>
                )}
              </Button>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}